import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { hideLayout: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { hideLayout: true }
  },
  {
    path: '/medicines',
    name: 'Medicines',
    component: () => import('../views/Medicines.vue')
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('../views/Cart.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/checkout',
    name: 'Checkout',
    component: () => import('../views/Checkout.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/orders/:id',
    name: 'OrderDetail',
    component: () => import('../views/OrderDetail.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/health',
    name: 'Health',
    component: () => import('../views/Health.vue')
  },
  {
    path: '/consultation',
    name: 'Consultation',
    component: () => import('../views/Consultation.vue')
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/Profile.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('../views/admin/Admin.vue'),
    meta: { requiresAuth: true, requiresAdmin: true, hideLayout: true },
    redirect: '/admin/medicines',
    children: [
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: () => import('../views/admin/Dashboard.vue'),
        meta: { hideLayout: true }
      },
      {
        path: 'medicines',
        name: 'AdminMedicines',
        component: () => import('../views/admin/Medicines.vue'),
        meta: { hideLayout: true }
      },
      {
        path: 'orders',
        name: 'AdminOrders',
        component: () => import('../views/admin/Orders.vue'),
        meta: { hideLayout: true }
      },
      {
        path: 'users',
        name: 'AdminUsers',
        component: () => import('../views/admin/Users.vue'),
        meta: { hideLayout: true }
      },
      {
        path: 'articles',
        name: 'AdminArticles',
        component: () => import('../views/admin/Articles.vue'),
        meta: { hideLayout: true }
      },
      {
        path: 'doctors',
        name: 'AdminDoctors',
        component: () => import('../views/admin/Doctors.vue'),
        meta: { hideLayout: true }
      },
      {
        path: 'consultations',
        name: 'AdminConsultations',
        component: () => import('../views/admin/Consultations.vue'),
        meta: { hideLayout: true }
      }
    ]
  },
  {
    path: '/pay/:orderId',
    name: 'Pay',
    component: () => import('../views/Pay.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  // 从localStorage获取认证信息
  const token = localStorage.getItem('token')
  const role = localStorage.getItem('role')
  const userId = localStorage.getItem('userId')
  const username = localStorage.getItem('username')
  
  // 判断用户是否已登录(有userId和role就认为已登录，更加灵活)
  const isLoggedIn = (userId && username && role) ? true : false
  
  console.log('路由守卫 - 当前路径:', to.path, 
              '认证状态:', isLoggedIn, 
              '角色:', role, 
              '用户:', username)
  
  // 登录页面直接放行
  if (to.path === '/login') {
    if (isLoggedIn) {
      // 已登录用户访问登录页，重定向到对应首页
      console.log('已登录用户访问登录页，重定向')
      if (role === 'admin') {
        next('/admin')
      } else {
        next('/')
      }
    } else {
      next()
    }
    return
  }

  // 注册页面无需登录
  if (to.path === '/register') {
    next()
    return
  }

  // 首页、药品页、养生知识、健康咨询无需登录
  if (to.path === '/' || to.path === '/medicines' || to.path === '/health' || to.path === '/consultation') {
    next()
    return
  }

  // 未登录用户重定向到登录页
  if (!isLoggedIn) {
    console.log('用户未登录，重定向到登录页面')
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return
  }

  // 保存上次访问的页面，以便刷新时恢复
  if (to.meta.requiresAuth && isLoggedIn) {
    localStorage.setItem('lastRoute', to.fullPath)
  }

  // admin路由权限控制
  if (to.path.startsWith('/admin')) {
    if (role === 'admin') {
      next()
    } else {
      console.log('非管理员用户尝试访问管理页面，重定向到首页')
      next('/')
    }
    return
  }

  // 普通用户路由控制
  if (role === 'admin') {
    // 管理员访问普通用户页面时重定向
    if (to.path === '/orders' || to.path.startsWith('/orders/')) {
      next('/admin/orders')
    } else if (to.path === '/cart' || to.path === '/checkout') {
      next('/admin')
    } else {
      next()
    }
  } else {
    // 普通用户访问需要验证的页面
    next()
  }
})

// 添加一个后置钩子来处理页面刷新恢复问题
router.afterEach((to) => {
  if (to.meta.requiresAuth && localStorage.getItem('token')) {
    localStorage.setItem('lastRoute', to.fullPath)
  }
})

export default router
